<script setup lang="ts">
import { ref, watch } from 'vue'
import { NesVue, type NesVueInstance } from 'nes-vue'
import type { IRomInfo } from '@/types'
import { ElMessage } from 'element-plus'

const props = defineProps<{ romInfo: IRomInfo }>()
let romUrl = ref('https://taiyuuki.github.io/nes-vue/Super Mario Bros (JU).nes')
let volume = ref(100)
const nesRef = ref<NesVueInstance>()
let isPlaying = ref(true)

watch(
  props,
  () => {
    console.log(props.romInfo)
    if (props.romInfo.url !== null && props.romInfo.url !== undefined) {
      romUrl.value = props.romInfo.url
    }
  },
  { immediate: true, deep: true }
)

/**
 * 游戏面板
 */
// 暂停游戏
watch(
  isPlaying,
  () => {
    if (isPlaying.value) {
      nesRef.value?.play()
    } else {
      nesRef.value?.pause()
    }
  },
  { immediate: true }
)

//切换游戏后更新 运行状态开关
watch(
  props,
  () => {
    if (props.romInfo) {
      isPlaying.value = true
    }
  },
  { immediate: true }
)
// 重启游戏
const handleReset = () => {
  nesRef.value?.reset()
  isPlaying.value = true
}
// 存档
const handleSave = () => {
  try {
    nesRef.value?.save(props.romInfo.id)
    ElMessage.success('存档成功：' + props.romInfo.id)
  } catch (e) {
    ElMessage.error('存档失败')
  }
}
// 读档
const handleLoad = () => {
  // 检查存档是否存在
  checkIfDataExists('nes-vue', 'save_data', props.romInfo.id)
    .then((exists) => {
      if (exists) {
        nesRef.value?.load(props.romInfo.id)
        ElMessage.success('读档成功：' + props.romInfo.id)
        isPlaying.value = true
      } else {
        ElMessage.error('没有存档哦')
      }
    })
    .catch((error) => {
      console.error('发生错误：', error)
    })
}

/**
 * 检查有无存档
 */
function checkIfDataExists(databaseName: string, tableName: string, id: string): Promise<boolean> {
  return new Promise((resolve, reject) => {
    const openRequest = indexedDB.open(databaseName)

    openRequest.onsuccess = function () {
      const db = openRequest.result
      //开启事务
      const transaction = db.transaction(tableName, 'readonly')
      const objectStore = transaction.objectStore(tableName)
      const request = objectStore.get(id)

      request.onsuccess = function () {
        const result = request.result
        resolve(!!result) // 如果找到数据，返回 true，否则返回 false
      }

      request.onerror = function () {
        reject('查找数据时出错')
      }
    }

    openRequest.onerror = function () {
      reject('打开数据库时出错')
    }
  })
}
</script>

<template>
  <div style="width: min-content">
    <NesVue
      ref="nesRef"
      :gain="volume"
      :label="'开始游戏🔥'"
      :width="512"
      :height="480"
      :url="romUrl"
    />
    <el-row :gutter="20" style="margin-top: 10px">
      <el-col :span="5">
        <el-row>
          <img src="@/assets/volume.svg" style="margin-right: 10px" />
          <el-slider v-model="volume" size="small" style="width: 50px" />
        </el-row>
      </el-col>
      <el-col :span="6">
        <el-switch
          v-model="isPlaying"
          size="small"
          active-text="继续"
          inactive-text="暂停"
          style="--el-switch-on-color: #13ce66; --el-switch-off-color: #ff4949"
        />
      </el-col>
      <el-col :span="3">
        <el-button type="warning" round size="small" @click="handleReset">重启</el-button>
      </el-col>
      <el-col :span="6">
        <el-button-group>
          <el-button round type="primary" size="small" @click="handleSave">存档</el-button>

          <el-button round type="primary" size="small" @click="handleLoad">读档</el-button>
        </el-button-group>
      </el-col>
    </el-row>
    <el-row :gutter="20">
      <el-col :span="24">
        <h3>键位说明</h3>
      </el-col>
      <el-col :span="6">玩家1</el-col>
      <el-col :span="4">
        <el-row justify="space-evenly">
          <el-tooltip content="开始" placement="top-end">
            <button>1</button>
          </el-tooltip>
          <el-tooltip content="选择" placement="top-start">
            <button>2</button>
          </el-tooltip>
        </el-row>
      </el-col>
      <el-col :span="5">
        <el-row justify="space-evenly"><button>W</button></el-row>
        <el-row justify="space-evenly">
          <button>A</button>
          <button>S</button>
          <button>D</button>
        </el-row>
      </el-col>
      <el-col :span="4">
        <el-row justify="space-evenly">
          <el-tooltip content="Y" placement="top-end">
            <button>U</button>
          </el-tooltip>
          <el-tooltip content="X" placement="top-start">
            <button>I</button>
          </el-tooltip>
        </el-row>
        <el-row justify="space-evenly">
          <el-tooltip content="B" placement="bottom-end">
            <button>J</button>
          </el-tooltip>
          <el-tooltip content="A" placement="bottom-start">
            <button>K</button>
          </el-tooltip>
        </el-row>
      </el-col>
    </el-row>
    <el-row :gutter="20" style="margin-top: 30px">
      <el-col :span="6">玩家2</el-col>

      <el-col :span="5">
        <el-row justify="space-evenly"><button>↑</button></el-row>
        <el-row justify="space-evenly">
          <button>←</button>
          <button>↓</button>
          <button>→</button>
        </el-row>
      </el-col>
      <el-col :span="4">
        <el-row justify="space-evenly">
          <el-tooltip content="Y" placement="top-end">
            <button>4</button>
          </el-tooltip>
          <el-tooltip content="X" placement="top-start">
            <button>5</button>
          </el-tooltip>
        </el-row>
        <el-row justify="space-evenly">
          <el-tooltip content="B" placement="bottom-end">
            <button>2</button>
          </el-tooltip>
          <el-tooltip content="A" placement="bottom-start">
            <button>1</button>
          </el-tooltip>
        </el-row>
      </el-col>
    </el-row>
  </div>
</template>

<style scoped></style>
